import BTControlNode from "../BTControlNode";
import { FAILURE, RUNNING, SUCCESS } from "../BTEnum";

/**
 * 顺序节点:
 * 从左到右依次执行其子分支，当第一次遇到当第一次遇到子分支返回失败时，
 * 则停止继续执行其他分支，此时Sequence返回失败，如果所有分支都返回成功，此时Sequence返回成功
 */
export default class BTSequence extends BTControlNode {
    private _index: number = 0;
    private _firstUpdate: boolean = true;
    update() {
        let node = this.children[this._index];
        if (this._firstUpdate) {
            node.start();
            this._firstUpdate = false;
        }
        let result = node.update();
        if (result !== RUNNING) {
            node.end();
            if (result === SUCCESS && this._index < this.children.length - 1) {
                result = RUNNING;
                this._firstUpdate = true;
                this._index++;
            }
        }
        return result;
    }
}
